﻿using Polly;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Brc_DSB.GetWay.Polly
{
    public class RetryHandler : DelegatingHandler
    {
        private readonly PollyRetryProvider _retryProvider;

        public RetryHandler(PollyRetryProvider retryProvider)
        {
            _retryProvider = retryProvider;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                if(_retryProvider.RetryPolicy.Policies.Length>0)
                {
                    return await Policy.WrapAsync(_retryProvider.RetryPolicy.Policies).ExecuteAsync(() => base.SendAsync(request, cancellationToken));
                }
                else
                {
                    return await base.SendAsync(request, cancellationToken);
                }
            }            
            catch (Exception ex)
            {                
                throw ex;
            }
        }
    }
}
